<template>
  <div class="app-container">
    <el-container>
      <el-aside width="80px" class="sidebar-container">
        <SidebarView @change-view="changeView" />
      </el-aside>
      <el-main class="main-container">
        <component :is="currentView" @open-chat="openChatDetail" />
      </el-main>
      <el-aside width="320px" class="rightbar-container" v-if="rightViewComponent">
        <component
          :is="rightViewComponent"
          v-bind="rightViewProps"
          @send-msg="handleSendMsg"
        />
      </el-aside>
    </el-container>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import SidebarView from './components/SidebarView.vue'
import ChatView from './components/ChatView.vue'
import ContactsView from './components/ContactsView.vue'
import DiscoverView from './components/DiscoverView.vue'
import MeView from './components/MeView.vue'
import ChatDetail from './components/ChatDetail.vue'

const views = {
  chat: ChatView,
  contacts: ContactsView,
  discover: DiscoverView,
  me: MeView
}
const currentView = ref(views.chat)
const rightViewComponent = ref(null)
const rightViewProps = ref({})

// 新增：所有用户的消息映射
const chatMessages = ref({}) // { [userId]: [msg, ...] }

const changeView = (view) => {
  currentView.value = views[view]
  rightViewComponent.value = null // 切换主视图时，右侧视图重置
}

const openChatDetail = (user) => {
  if (!chatMessages.value[user.id]) {
    chatMessages.value[user.id] = [
      { id: 1, text: `你好，我是${user.name}。`, isSelf: false },
      { id: 2, text: '你好！很高兴认识你。', isSelf: true },
      { id: 3, text: '我们来聊聊吧。', isSelf: false }
    ]
  }
  rightViewComponent.value = ChatDetail
  rightViewProps.value = {
    user,
    messages: chatMessages.value[user.id]
  }
}

// 新增：处理消息发送
const handleSendMsg = ({ userId, text }) => {
  chatMessages.value[userId].push({
    id: Date.now(),
    text,
    isSelf: true
  })
  // 重新赋值触发响应式
  if (rightViewProps.value.user && rightViewProps.value.user.id === userId) {
    rightViewProps.value = {
      ...rightViewProps.value,
      messages: [...chatMessages.value[userId]]
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  height: 100vh;
  display: flex;

  .sidebar-container {
    background-color: #f7f7f7;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
    align-items: center;
    // padding-top: 20px;
  }

  .main-container {
    padding: 0;
    background-color: #fff;
  }
}
.rightbar-container {
  background: #fafbfc;
  border-left: 1px solid #e6e6e6;
  padding: 0;
}
</style>
